<?php

namespace backend\controllers;
use common\models\Active;
use common\models\ActiveAttr;
use common\models\AttributeDeion;
use common\models\City;
use common\models\Code;
use common\models\Goods;
use common\models\GoodsAttr;
use common\models\Shop;
use common\models\Tree;
use common\service\ActiveService;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\LogaddService;
use common\service\GoodsService;
//use common\models\Googs;
//use common\models\GoogsAttr;
//use common\models\Activity;
//use common\models\ActivityAttr;
use common\models\Admin;
use common\models\Order;
use common\service\GlobalUrlService;
use common\service\WechatService;
use common\models\GoodsImg;
class ShopController extends BaseController
{
    /**
     * 列表
     * @return string
     */
    public function actionIndex(){
        if($this->isAjax() && $this->isGet()){
            $query = Shop::find();
            if(!empty($this->get('shop_name'))){
                $query->andWhere(['like','shop_name',$this->get('shop_name')]);
            }
            if(!empty($this->get('status'))){
                $query->andWhere(['status'=>$this->get('status')-1]);
            }
            if(!empty($this->get('type'))){
                $query->addWhere(['type'=>$this->get('type')-1]);
            }
            $p = intval( $this->get('page',1) );
            $this->page_size = intval( $this->get('limit',10) );
            $p = ( $p > 0 )? $p : 1;
            $count = $query->count();

            $offset = ($p - 1) * $this->page_size;

            $lists = $query->orderBy(['create_time' => SORT_DESC, 'id' => SORT_DESC])
                ->offset( $offset )
                ->limit( $this->page_size )
                ->asArray()
                ->all();

            return $this->renderPageJson($lists,$count,ConstantService::$response_tab_success);
        }
        $status = $this->get('status',0);
        return $this->render('index',['status'=>$status]);

    }

    /**
     * 添加
     */
    public function actionAddShop(){
        if($this->isAjax() && $this->isPost()){
            $data = $this->post();

            $re_code = $this->_checkcode($data['admin_phone'],$data['code']);
            if($re_code !== true){
                return $this->renderJson([],$re_code,ConstantService::$response_fail);
            }
            $msg = $this->_validation($data,true);
            if($msg !== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            $model = new Shop();
            $data['password'] = md5(md5($data['password']).$this->salt);
            $data['status'] = 0;
            $data['create_time'] = time();
            $data['update_time'] = time();
            $model->setAttributes($data);
            if($model->save()){
                $Codes = Code::findOne(['id'=>$re_code]);
                $Codes->is_del = 1;
                $Codes->save();
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'新增店铺'.$data['shop_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'新增成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'新增失败',ConstantService::$response_fail);
            }
        }
        return $this->render('add-shop');
    }

    /**
     * 修改
     */
    public function actionUpdateShop(){
        if($this->isPost() && $this->isAjax()){
            $data = $this->post();
            $msg = $this->_validation($data,false);
            if($msg !== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            if(!empty($data['password'])){
                $data['password'] = md5(md5($data['password']).$this->salt);
            }else{
                unset($data['password']);
            }
            $shop_model = Shop::findOne(['id'=>$data['id']]);

            $data['update_time'] = time();
            $shop_model->setAttributes($data);
            if($shop_model->save()){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'修改店铺'.$data['shop_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'修改成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'修改失败',ConstantService::$response_fail);


        }
        $id = $this->get('id');
        $data = Shop::find()->where(['id'=>$id])->asArray()->one();
        return $this->render('update-shop',['row'=>$data]);
    }

    /**
     * 修改状态,停用或者启用
     */
    public function actionModifyStatus(){
        if($this->isAjax() && $this->isPost()){
            $id = $this->post('id');
            $status = $this->post('status');
            if(!in_array($status,[1,3])){
                return $this->renderJson([],'状态值错误',ConstantService::$response_fail);
            }
            $shop_model = Shop::findOne(['id'=>$id]);
            $shop_model->status = $status;
            if ($shop_model->save()){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'修改店铺状态'.$shop_model['shop_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'操作成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'操作失败',ConstantService::$response_fail);
        }
        return $this->renderJson([],'接口错误',ConstantService::$response_fail);

    }

    /**
     * 驳回
     */
    public function actionModifyStatustoregect(){
        if($this->isPost() && $this->isAjax()){
            $status = 2;
            $dismissal = $this->post('dismissal');
            $id = $this->post('id');
            $shop_model = Shop::findOne(['id'=>$id]);
            $shop_model->status = $status;
            $shop_model->dismissal = $dismissal;
            if ($shop_model->save()){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'修改店铺状态'.$shop_model['shop_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'操作成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'操作失败',ConstantService::$response_fail);
        }
        return $this->renderJson([],'接口错误',ConstantService::$response_fail);
    }

    /**
     *查看
     */
    public function actionGetInfo(){
        $id = $this->get('id');
        $data = Shop::find()->where(['id'=>$id])->asArray()->one();
        return $this->render('get-info',['row'=>$data]);

    }

    /**
     * 验证填入字段是否正确
     * @param array $data
     * @param bool $type
     * @return string
     */
    private function _validation($data = array(),$type = true){

        if(empty($data['shop_name'])){
            return "店铺名称不能为空";
        }
        if(empty($data['user_account'])){
            return "店铺登录账号不能为空";
        }
        if(!preg_match('/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$/',$data['admin_phone'])) {
            return '请输入正确的管理员手机号';
        }
        if(empty($data['administration'])){
            return "店铺管理姓名不能为空";
        }
        if(!preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$data['admin_email'])) {
            return '请输入正确的管理员邮箱';
        }

        if(empty($data['join_card_no'])){
            return "店铺管理人身份证不能为空";
        }
        if(empty($data['join_card1_pic'])){
            return "店铺管理人身份证正面照不能为空";
        }
        if(empty($data['join_card2_pic'])){
            return "店铺管理人身份证反面照不能为空";
        }

        if(empty($data['join_card3_pic'])){
            return "店铺管理人手持身份证照片不能为空";
        }

        $data_shop_name = Shop::findOne(['shop_name'=>$data['shop_name']]);
        $data_user_account = Shop::findOne(['user_account'=>$data['user_account']]);
        $data_admin_phone = Shop::findOne(['admin_phone'=>$data['admin_phone']]);
        $customer_phone = Shop::findOne(['customer_phone'=>$data['customer_phone']]);

        if($type){
            //新增
            if(!empty($data_shop_name)){
                return "已经存在同名店铺";
            }
            if(!empty($data_user_account)){
                return "已经存在同名登录账号";
            }
            if(!empty($data_admin_phone)){
                return "已经存在同名管理员电话号码";
            }
            if(empty($data['password'])){
                return "店铺管理密码不能为空";
            }
            if(!empty($customer_phone)){
                return "商家客服电话已存在";
            }
        }else{
            //修改
            if(!empty($data_shop_name) && $data['id'] != $data_shop_name['id']){
                return "已经存在同名店铺";
            }
            if(!empty($data_user_account) && $data['id'] != $data_user_account['id']){
                return "已经存在同名登录账号";
            }
            if(!empty($data_admin_phone) && $data['id'] != $data_admin_phone['id']){
                return "已经存在同名管理员电话号码";
            }
            if(!empty($customer_phone) && $data['id'] != $customer_phone['id']){
                return "已经存在同名管理员电话号码";
            }

        }
        return true;
    }


        /**
     * 验证验证码是否正确
     * @param $phone
     * @param $code
     * @return string
     */
    private function _checkcode($phone,$code){
        if(empty($phone)){
            return '管理员手机号不能为空!';
        }
        if( empty($code)){
            return '验证码不能为空!';
        }
        $data = Code::find()->where(['phone'=>$phone])->orderBy(['id'=>SORT_DESC])->one();
        if((time()-$data['time'])>300 || $data['is_del'] == 1){
            return '验证码错误';
        }
        if($data['code'] == $code){
            return true;
        }else{
            return '验证码错误';
        }
    }

    /**
     * 查看商家商品
     */
    public function actionGoodsIndex(){
        if($this->isGet() && $this->isAjax()){
            $Googs = Goods::find();

            $goods_name = $this->get('goods_name');
            $tree_id = $this->get('tree_id');
            $id = $this->get('id');
            $two_id = $this->get('two_id');
            $three_id = $this->get('three_id');

            $Googs->andWhere(['shop_id'=>$id]);
            $Googs->andWhere(['is_del'=>0]);
            if($goods_name){
                $Googs->andWhere(['like','goods_name',$goods_name]);
            }
            if($tree_id){
                $Googs->andWhere(['one_tree_id'=>$tree_id]);
            }
            if($two_id){
                $Googs->andWhere(['two_tree_id'=>$two_id]);
            }

            if($three_id){
                $Googs->andWhere(['three_tree_id'=>$three_id]);

            }
            $p = intval( $this->get('page',1) );
            $this->page_size = intval( $this->get('limit',10) );
            $p = ( $p > 0 )? $p : 1;
            $count = $Googs->count();

            $offset = ($p - 1) * $this->page_size;
            $data = $Googs->select('goods_name,sales_volume,status,id,shop_id')
                ->limit($this->page_size)
                ->offset($offset)
                ->asArray()
                ->all();

            $googsModel = new Goods();
            $lists = $googsModel->GetgoogsList($data,1);
            return $this->renderPageJson($lists,$count,ConstantService::$response_tab_success);
        }
        $id = $this->get('id');
        $trees = Tree::find()->where(['level'=>'1'])->asArray()->all();
        return $this->render('goods-index',['trees'=>$trees,'id'=>$id]);
    }

    /**
     * 商家商品详情
     * @return string|void
     */
    public function actionGoogsInfo(){
        $googs_id = $this->get('id');
        $shop_id = $this->get('shop_id');
        if(!$googs_id){
            return $this->renderJson([],'缺少参数',ConstantService::$response_fail);
        }

        $goods = Goods::find()->where(['id'=> $googs_id])->asArray()->one();

        $goodsimg = GoodsImg::find()->select('img_url')->where(['goods_id'=>$googs_id,'status'=>1])->asArray()->all();
        $goods['banner'] = $goodsimg;

        $googsattr = GoodsAttr::find()->where(['goods_id' => $googs_id,'is_del'=>0])->orderBy(['id'=>SORT_ASC])->asArray()->all();
        $onetree = Tree::find()->where(['pid'=>0])->asArray()->all();
        $twotree = Tree::find()->where(['pid'=>$goods['one_tree_id']])->asArray()->all();
        $threetree = Tree::find()->where(['pid'=>$goods['two_tree_id']])->asArray()->all();
        $attrlists = GoodsService::GetAttrlist($googs_id);
        $deion = AttributeDeion::find()
            ->select('id,key,val')
            ->where(['goods_id'=>$googs_id])
            ->asArray()
            ->all();

        return $this->render('goods-info',[
            'id' => $shop_id,
            'onetree' => $onetree,
            'twotree' => $twotree,
            'threetree' => $threetree,
            'attrlist' => $attrlists,
            'goods' => $goods,
            'googsattr' => $googsattr,
            'attr_des' => $deion,
            'attr_count' => count($googsattr)
        ]);
    }



    //活动列表页
    public function actionActivity(){
        if($this->isAjax() && $this->isGet()){
            $name=$this->get('name');
            $shopid=$this->get('id');
            $ac_query = Active::find();

            if(!empty($name)){
                $ac_query->andWhere(['like','active_name',$name]);
            }
            $ac_query->andWhere(['shop_id'=>$shopid]);
            $ac_query->andWhere(['is_del'=>0]);
            $p = intval( $this->get('page',1) );
            $this->page_size = intval( $this->get('limit',10) );
            $p = ( $p > 0 )? $p : 1;
            $count = $ac_query->count();

            $offset = ($p - 1) *  $this->page_size;
            $lists = $ac_query->offset($offset)
                ->limit($this->page_size)
                ->orderBy('create_time ',SORT_DESC)
                ->asArray()
                ->all();
            return $this->renderPageJson($lists,$count,ConstantService::$response_tab_success);
        }
        $shopid=$this->get('id');
        return $this->render('activity_index',['id'=>$shopid]);
    }

    //暂停活动
    public function actionEnd(){
        if($this->isAjax() && $this->isPost()){
            $id=$this->post('id');
            $data = Active::find()->where(['id'=>$id])->one();
            $data['status']=3;
            $re=$data->save();
            if ($re){
                return $this->renderJson([],'禁用成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'禁用失败',ConstantService::$response_fail);
            }
        }
    }

    //查询活动详情  这个应该是有问题的
    public function actionSelect(){

        $aid = $this->get('id');
        $shop_id = $this->get('shop_id');
        $active = Active::findOne(['id'=>$aid]);

        $activeAttr = ActiveService::GetAttrlist($aid);
        return  $this->render('select',[
            'active_attr'=>$activeAttr,
            'active'=>$active,
            'shop_id' => $shop_id,
            'id' => $aid
        ]);
    }

    /**
     * 设置提现服务费用
     */
    public function actionSetServiceRate(){
        if($this->isPost() && $this->isAjax()){
            $id = $this->post('id');
            $service_rate = $this->post('value');
            $shop = Shop::findOne(['id'=>$id]);
            $shop->service_rate = $service_rate;
            if($shop->save()){
                return $this->renderJson([],'设置成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'设置失败,请稍后再试',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

}